//
//  CommentsViewController.m
//  Final
//
//  Created by lanou3g on 15/12/4.
//  Copyright © 2015年 皮比诺. All rights reserved.
//

#import "CommentsViewController.h"
#import "CommentsTableViewCell.h"
#import "MessageViewController.h"

@interface CommentsViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView * commentsTabelView;
@property (nonatomic,strong)UIView * inputView;
@property (nonatomic,strong)AVObject * comment;
@property (nonatomic,strong)NSMutableArray * dataArray;
@property (nonatomic,strong)UITextField * commentsTextField;
@property(assign,nonatomic)NSInteger keyHieght;
@property(copy,nonatomic)NSString *commentContent;
@property (nonatomic,strong)NSString * numeber;

@property (strong, nonatomic)UILabel *headLabel;
@property (nonatomic,strong)UILabel * headNameLabel;
@property(strong,nonatomic)UIImageView *headImageView;
@property (nonatomic,assign) CGFloat headLabelHeight;
@property (nonatomic,strong)AVQuery * query;

@property (nonatomic,copy)NSString * cellContent;

@end

@implementation CommentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 评论 列表
    self.commentsTabelView = [[UITableView alloc] init];
    self.commentsTabelView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 99);
    self.tabBarController.tabBar.hidden = YES;

    self.commentsTabelView.frame = [UIScreen mainScreen].bounds;
    self.dataArray = [NSMutableArray array];
//    AVQuery * query = [AVQuery queryWithClassName:@"Comment"];
//    [query whereKey:@"messageid" equalTo:self.myObject.objectId];
//    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//        
//        if (!error) {
//            [self.dataArray setArray:objects];
//            [query orderByDescending:@"createdAt"];
//            [self.commentsTabelView reloadData];
//        }
//    }];
    // 发送的View
    self.inputView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50, [UIScreen mainScreen].bounds.size.width, 50)];
    self.inputView.backgroundColor = [UIColor whiteColor];
    self.commentsTextField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, [UIScreen mainScreen].bounds.size.width-60-5, 40)];
   self.commentsTextField.placeholder = @"请输入评论内容!";
     self.commentsTextField.backgroundColor = [UIColor grayColor];
    [self.inputView addSubview:self.commentsTextField];
    UIButton * sendButton = [UIButton buttonWithType:UIButtonTypeSystem];
    sendButton.frame = CGRectMake(self.view.frame.size.width-55, 5, 40, 40);
    sendButton.backgroundColor = [UIColor grayColor];
    [sendButton setTitle:@"发送" forState:(UIControlStateNormal)];
    [sendButton addTarget:self action:@selector(sendButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.inputView addSubview:sendButton];

    // 注册键盘出现的通知,为了动态获取键盘高度
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    // 微博的、内容
    self.headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    self.headImageView.layer.cornerRadius = 10;
    self.headImageView.layer.masksToBounds = YES;
        self.headImageView.backgroundColor = [UIColor orangeColor];
    AVFile * attachment = [self.myObject objectForKey:@"userImage"];
    AVFile * file = [AVFile fileWithURL:attachment.url];
    [file getThumbnail:YES width:50 height:50 withBlock:^(UIImage *image, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@",image);
            
            self.headImageView.image = image;
        });
    }];
    self.headNameLabel = [[UILabel alloc] init];
    self.headNameLabel.frame = CGRectMake(70, 20, 100, 30);
    self.headNameLabel.text = [self.myObject objectForKey:@"userName"];
    self.headLabel = [[UILabel alloc] init];
    self.headLabel.numberOfLines = 0;
    self.headLabel.text = [self.myObject objectForKey:@"message"];
    self.headLabelHeight = [self heightOfTouLab:[self.myObject objectForKey:@"message"]];
    
    
    self.headLabel.frame = CGRectMake(100, 70, self.view.frame.size.width-20-120, self.headLabelHeight);
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, (self.headLabel.frame.size.height > 100 ? self.headLabel.frame.size.height+20 : 100+20))];
    [v addSubview:self.headImageView];
    [v addSubview:self.headNameLabel];
    [v addSubview:self.headLabel];
    self.commentsTabelView.tableHeaderView = v;
    // 注册cell
    [self.commentsTabelView registerClass:[CommentsTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.commentsTabelView.delegate = self;
    self.commentsTabelView.dataSource = self;
    [self.view addSubview:self.commentsTabelView];
    [self.view addSubview:self.inputView];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:nil target:self action:@selector(backAction:)];
    
    
    [self down];
}
// 返回按钮
- (void)backAction:(id)sender
{
    self.tabBarController.tabBar.hidden = NO;
   
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    
    return YES;
}

// 收键盘、发送、显示、取值、刷新
-(void)sendButtonAction:(id)sender
{
    [self P_makeData];
   self.commentContent= self.commentsTextField.text;
    
    if (self.commentContent.length != 0) {
        [self loadData];
    }
    
    self.commentsTextField.text = NULL;
    
}
// textFiled
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSInteger h = (NSInteger)keyboardRect.size.height;
    _keyHieght = h;
    // 动画效果
    [UIView animateWithDuration:0.4 animations:^{
        
        self.inputView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50 -_keyHieght, [UIScreen mainScreen].bounds.size.width, 50);
    }];
}
// 微博内容自适应
- (CGFloat)heightOfTouLab:(NSString *)string
{
    CGRect r = [string boundingRectWithSize:CGSizeMake(self.view.frame.size.width-140, 2000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19.5f]} context:nil];
       return r.size.height;
}
// 回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self P_makeData];
    
    return YES;
}

- (void)P_makeData
{
    [self.commentsTextField resignFirstResponder];
    
    // 改变frame
    [UIView animateWithDuration:0.3 animations:^{
        
        self.inputView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50, [UIScreen mainScreen].bounds.size.width, 50);
    }];
}

// 加载数据
-(void)loadData{
    
        // 存储数据
        NSString *s = self.commentContent;
                // 创建评论表
        self.comment = [AVObject objectWithClassName:@"Comment"];
   
        [self.comment setObject:s forKey:@"comment"];
        [self.comment setObject:self.myObject.objectId forKey:@"messageid"];
        
        [self.comment  setObject:[AVUser currentUser].username forKey:@"UserName"];
        [self.comment  saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [self down];
            }
        }];
  
}
- (void)down{
    AVQuery * query = [AVQuery queryWithClassName:@"Comment"];
    // AVQuery
    [query orderByDescending:@"createdAt"];

   
    [query whereKey:@"messageid" equalTo:self.myObject.objectId];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if (!error) {
            [self.dataArray setArray:objects];
            [query orderByDescending:@"createdAt"];
            [self.commentsTabelView reloadData];
          
        }
    }];
}
#pragma mark--- tableView 代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentsTableViewCell * cell = [tableView  dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    
    AVObject * object = self.dataArray[indexPath.row];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@ 说:",[object objectForKey:@"UserName"]];
    cell.commentsLabel.text = [object objectForKey:@"comment"];
    self.cellContent = cell.commentsLabel.text;
    cell.commentsLabel.numberOfLines = 0;
    return cell;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
       return [NSString stringWithFormat:@"评论(%ld)",self.dataArray.count];
}
// 头部高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    
    return 30;
}
// 评论 自适应
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGRect r = [self.cellContent boundingRectWithSize:CGSizeMake(self.view.frame.size.width-100, 2000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18.0f]} context:nil];
    return 30 + r.size.height;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
